package com.parking.status.sync.netty.server;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.parking.status.sync.netty.entity.MessageType;
import com.parking.status.sync.netty.entity.RequestPre;
import com.parking.status.sync.netty.util.PojoMapper;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.util.List;

/**
 * Created by Administrator on 2015/9/18.
 */
public class RequestBodyDecoder extends MessageToMessageDecoder<String> {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, String messageBody, List<Object> out) throws Exception {

        ObjectMapper mapper = new ObjectMapper();
        //JSON ----> JsonNode
        JsonNode rootNode = mapper.readTree(messageBody);
        JsonNode codeNode = rootNode.get(MessageType.FIELD_NAME_CODE);
        String msgType = codeNode.toString();

        RequestPre request = null;
        Class<? extends RequestPre> classtype = MessageType.getMessageClass(msgType);
        if (classtype != null) {
            request = PojoMapper.fromJson(messageBody, classtype);
        } else {
            //TODO
            //request = new RequestError("unknow code error");
        }

        out.add(request);
    }
}